package example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 数据库连接池单例
 */
public class DatabaseConnectionPool {
    
    private static volatile DatabaseConnectionPool instance;
    private final BlockingQueue<Connection> connectionPool;
    private final String url;
    private final String username;
    private final String password;
    private final int poolSize;
    
    private DatabaseConnectionPool() {
        // 初始化连接池参数
        this.url = "jdbc:mysql://localhost:3306/mydb";
        this.username = "root";
        this.password = "password";
        this.poolSize = 10;
        this.connectionPool = new LinkedBlockingQueue<>(poolSize);
        
        initializePool();
    }
    
    public static DatabaseConnectionPool getInstance() {
        if (instance == null) {
            synchronized (DatabaseConnectionPool.class) {
                if (instance == null) {
                    instance = new DatabaseConnectionPool();
                }
            }
        }
        return instance;
    }
    
    private void initializePool() {
        try {
            for (int i = 0; i < poolSize; i++) {
                Connection connection = DriverManager.getConnection(url, username, password);
                connectionPool.offer(connection);
            }
        } catch (SQLException e) {
            throw new RuntimeException("初始化数据库连接池失败", e);
        }
    }
    
    public Connection getConnection() throws InterruptedException {
        return connectionPool.take();
    }
    
    public void releaseConnection(Connection connection) {
        if (connection != null) {
            connectionPool.offer(connection);
        }
    }
    
    public int getAvailableConnections() {
        return connectionPool.size();
    }
}